/**
 * Created by lenovo on 2017/8/22.
 */
var fs = require('fs'),
    path = require('path'),
    conf = JSON.parse(fs.readFileSync(path.join(__dirname, '../../../') + './conf.json')),
    utils = require('../utils/common'),
    logInfoBiz = require('../biz/log-info-biz'),
    filter = {
    requestFilter: function (req, res, next) {
        var url = req.originalUrl,
            secuParam = {},
            strTime = utils.dateFormatter(new Date(),"yyyy-MM-dd hh:mm:ss"),
            newUrl = "https://"+conf.hostIP+"/"+conf.welcome;

        if(conf.env === "pro" && req.protocol === "http"){
            logInfoBiz.create({
                ip: getClientIp(req),
                type: req.method,
                url: url,
                remark: strTime+"【 请求重定向, 客户端ip: "+ getClientIp(req)+"】,原始url = "+url+"，新url="+newUrl
            });
            return res.redirect(newUrl);
        }

        if (url.indexOf("/logout")===-1 && url!= "/index.html" && url!= "/" && url.indexOf("/login")===-1 && !req.session.userInfo) {
            logInfoBiz.create({
                ip: getClientIp(req),
                type: req.method,
                url: url,
                remark: strTime+"【 session 失效："+url+" ;客户端ip: "+ getClientIp(req)+"】"
            });
            return res.redirect("/");
        }
        next();
    }
};

function getClientIp(req) {
    return  req.headers['x-real-ip'] ||
        req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
};

module.exports = filter;